'use strict';

const {
	isObject
} = require("util");

const db = uniCloud.database()
const userInfoDBName = 'zhy_user_info'
const businessInfoDBName = 'zhy_business_info'
const userConsumeDBName = 'zhy_consume_record'
const userAllowenceDBName = 'zhy_allowence_record'
const queueDBName = 'zhy_comsume_queue'

/**
 * 处理补贴和消费记录：
 * 添加/删除
 */
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	// let maxOrder = await getMaxConsumeOrder('111')
	// console.log(maxOrder);
	// let a = await getUserComsumeByAllowencing('111', '222')
	// console.log(JSON.stringify(a));
	// updateUserConsumeStatus('111', '222', 3)
	if (event.operateType === 1) {
		// 在本系统支付成功后 -- 使用聚合支付
		// 保存补贴和消费记录，修改用户在花币和红包数量,增加排队
		return afterAggrePaySuccess(event, context)
	} else if (event.operateType === 2) {
		// 用户提现后--补贴记录不用删除，修改消费记录的状态：3，修改用户在花币和红包数量，删除(逻辑删除)排队
		return afterUserWithdrawSuccess(event, context)
	} else if (event.operateType === 3) {
		// 用户在第三方平台消费支付成功后：新增消费记录,新增补贴记录，修改用户在花币和红包数量，增加排队
		return afterUserPayOnThirdPartySuccess(event, context)
	}

	//返回数据给客户端
	// return event
	return ''
};

async function afterAggrePaySuccess(event, context) {
	/*
	{
		消费记录
		user_id:'',
		business_id:'',
		consume_time:'timestamp',
		consume_amount:'',// 消费金额：分
		max_allowence_amount：//最大补贴金额，单位：分，不能超过，超过则修改状态为：已完
		// 以下参数不需要，默认赋值
		consume_status:1,//消费状态:1补贴中，2已完成，3已退出
	    consume_from:1,//消费来自:1.自己平台消费。 2.三方平台
		thirdPartyInfo:{}// 三方商户信息：名称等信息（order_title，brand_id）
		
		补贴记录
		bs_reverse_allowence_amount:1,
		zhb_allowence_amount:1,
		// 以下参数不需要，默认赋值
		allowence_time://
		
		// 排队
		pay_time：时间戳
	}
	*/
	// ---ok
	// 1.添加消费记录：只需要保证只有一条 补贴中 的消费记录。同一用户在同一商家消费：补贴中的消费记录只有一条。已完成/已退出的状态可以有多条
	let addConsumeSucess = await addUserConsumeRecord(event, '1')
	if (!addConsumeSucess) {
		console.log('添加消费记录失败');
		return 0
	}
	// ---ok
	// 2.添加补贴记录：注意不要超出消费记录的最大补贴金额
	let addAllowenceSuccess = await addUserAllowenceRecord(event)
	if (!addAllowenceSuccess) {
		// 失败原因只有：超出消费的最大补贴金额。应该不存在失败：添加补贴前后都会去判断
		console.log('添加补贴记录失败');
		// 删除消费记录
		// removeConsumeRecord(addConsumeSucess._id)
		return 1
	}
	let allowenceAmountFen = addAllowenceSuccess.zhb_num
	// ---ok
	// 3.修改用户在花币和红包：在花币增加x，红包就会对应减少x
	let updateUserResult = await updateUserZhbAndRedWallet(event.user_id, allowenceAmountFen, 1,
		allowenceAmountFen, -1) // 返回true/false

	// ---ok
	// 4.修改商户的备付金:补贴之后都是减少对应的备付金 // 返回true/false
	let updateBusinessInfo = await updateBusinessReserveAmount(event.business_id, allowenceAmountFen)

	// ---ok
	// 5.新增排队：商家队列中已存在该用户，不会重复添加---补贴即可，补贴结束就删除（逻辑删除）
	let addQuequeResult = await addQueue(event) // 返回addResult/false

	// ---ok
	// 6.删除用户排队队列:当消费记录无 补贴中的状态就去 逻辑删除队列
	let removeQueueResult = await removeQueueIfExitOrFinished(event.business_id, event.user_id)
	return true
}

async function afterUserWithdrawSuccess(event, context) {
	// 补贴记录不用删除，修改消费记录的状态：3，修改用户在花币和红包数量，删除(逻辑删除)排队
	let updateConsumeResult = await updateUserConsumeStatus(event.business_id, event.user_id, 3)
	let removeQueueResult = await removeQueueIfExitOrFinished(event.business_id, event.user_id)
	// todo lxw 如何确定减去的在花币数量
	let updateUserResult = await updateUserZhbAndRedWallet(event.user_id, 0, 1, 0, -1) // 返回true/false
	return true
}

async function afterUserPayOnThirdPartySuccess(event, context) {

}

//=========================================================非主函数======================================================//
// 修改用户的在花币和红包数量
async function updateUserZhbAndRedWallet(userId, zhb_num, zhbAscOrDesc, red_wallet, redWalletAscOrDesc) {
	if (zhb_num == 0 && red_wallet == 0) {
		console.log('在花币新增为0，无需改动');
		return false
	}
	const userInfoCollection = db.collection(userInfoDBName)
	let userInfoResult = await userInfoCollection.where({
		user_id: userId
	}).limit(1).get()
	let userExist = unicloudDataExist(userInfoResult)
	if (!userExist) {
		console.log('用户不存在：' + userId);
		return
	}
	let userInfo = userInfoResult.data[0]
	let updateParam = {
		zhb_num: userInfo.zhb_num,
		red_wallet: userInfo.red_wallet,
	}
	if (zhbAscOrDesc == 1) {
		// 在花币增加
		updateParam.zhb_num = userInfo.zhb_num + zhb_num
	} else if (zhbAscOrDesc == -1) {
		// 在花币减少
		updateParam.zhb_num = userInfo.zhb_num - zhb_num
	}

	if (redWalletAscOrDesc == 1) {
		// 在花币增加
		updateParam.red_wallet = userInfo.red_wallet + red_wallet
	} else if (redWalletAscOrDesc == -1) {
		// 在花币减少
		updateParam.red_wallet = userInfo.red_wallet - red_wallet
	}
	await userInfoCollection.doc(userInfo._id).update(updateParam);
	return true
}

// 判断unicloud查询结果是否存在
function unicloudDataExist(obj) {
	if (obj == null || obj == undefined || obj == '' || JSON.stringify(obj) == '{}') {
		return false
	}
	if (obj.data == null || obj.data.length == 0) {
		return false
	}
	return true
}

// 判断对象是否为空
function objIsEmpty(obj) {
	if (obj == null || obj == undefined || obj == '' || JSON.stringify(obj) == '{}') {
		return true
	}
	return false
}

// 新增消费记录
async function addUserConsumeRecord(event, consume_from) {
	// 参数校验
	if (objIsEmpty(event)) {
		console.log('参数为空');
		return false
	}
	if (objIsEmpty(event.user_id)) {
		console.log('user_id为空');
		return false
	}
	if (objIsEmpty(event.business_id)) {
		console.log('business_id为空');
		return false
	}
	if (objIsEmpty(event.consume_time)) {
		console.log('consume_time为空');
		return false
	}
	if (objIsEmpty(event.consume_amount)) {
		console.log('consume_amount为空');
		return false
	}
	if (objIsEmpty(event.max_allowence_amount)) {
		console.log('max_allowence_amount为空');
		return false
	}
	// 判断是否已存在消费：不可重复添加补贴中的消费
	let allowendingConsume = await getUserComsumeByAllowencing(event.business_id, event.user_id)
	if (allowendingConsume != null) {
		// 有则不添加
		console.log('无需重复添加补贴中的消费记录');
		return true
	}
	// 不存在补贴中的，直接添加
	let userConsumeCollection = db.collection(userConsumeDBName)
	let consumeParam = {
		user_id: event.user_id,
		business_id: event.business_id,
		consume_time: event.consume_time,
		consume_amount: event.consume_amount,
		consume_status: 1, //消费状态:1补贴中，2已完成，3已退出
		consume_from: consume_from, //消费来自:1.自己平台消费。 2.三方平台
		max_allowence_amount: event.max_allowence_amount, //最大补贴金额：分
	}
	let addUserConsumeResult = await userConsumeCollection.add(consumeParam)
	if (objIsEmpty(addUserConsumeResult)) {
		return false
	}
	if (addUserConsumeResult._id == null || addUserConsumeResult == undefined || addUserConsumeResult == '') {
		return false
	}
	return addUserConsumeResult
}

// 获取用户在某商家消费的记录，没有则返回null
async function getUserComsumeByAllowencing(business_id, user_id) {
	let result = await db.collection(userConsumeDBName).where({
		user_id: user_id,
		business_id: business_id,
		consume_status: 1,
	}).limit(1).get()
	// {"affectedDocs":0,"data":[]}
	let exist = unicloudDataExist(result)
	if (exist) {
		return result.data[0]
	}
	return null
}

// 新增补贴记录
// 返回false/{zhb_num:1}
async function addUserAllowenceRecord(event) {
	// 参数校验
	if (objIsEmpty(event)) {
		console.log('参数为空');
		return false
	}
	if (objIsEmpty(event.user_id)) {
		console.log('user_id为空');
		return false
	}
	if (objIsEmpty(event.bussiness_id)) {
		console.log('bussiness_id为空');
		return false
	}
	if (objIsEmpty(event.bs_reverse_allowence_amount)) {
		console.log('bs_reverse_allowence_amount为空');
		return false
	}
	if (objIsEmpty(event.zhb_allowence_amount)) {
		console.log('zhb_allowence_amount为空');
		return false
	}
	// 获取当前消费记录:判断是否超出补贴最大金额。新增前后都应该判断
	let consumeRecord = await getUserComsumeByAllowencing(event.business_id, event.user_id)
	// 获取补贴了的所有记录
	let allowenedZHB = await getAllAllowencedZHBNum(consumeRecord._id)
	let max = consumeRecord.max_allowence_amount
	let pre = event.zhb_allowence_amount + allowenedZHB
	let addZHB = 0
	let isFinished = false
	if (max <= pre) {
		addZHB = max - allowenedZHB
		isFinished = true
	}
	if (addZHB <= 0) {
		return {
			zhb_num: 0
		}
	}
	let allowenceParam = {
		user_id: event.user_id,
		business_id: event.business_id,
		bs_reverse_allowence_amount: addZHB, // 商户补贴的和用户的在花币一致
		zhb_allowence_amount: addZHB,
		allowence_time: new Date().getTime(),
		consume_id: consumeRecord._id
	}
	let addResult = db.collection(allowenceParam).add(allowenceParam)
	if (objIsEmpty(addResult)) {
		return false
	}
	if (addResult._id == null || addResult == undefined || addResult == '') {
		return false
	}
	if (isFinished) {
		// 修改状态已完成
		let updateConsumeResult = await updateUserConsumeStatus(event.business_id, event.user_id, 2)
	}
	// 判断是否超出补贴最大金额。新增前后都应该判断
	let res = {
		consume_id: consumeRecord._id,
		zhb_num: addZHB,
		isFinished: isFinished
	}
	return res
}

// 删除消费记录
function removeConsumeRecord(consumeId) {
	if (objIsEmpty(consumeId)) {
		return false
	}
	db.collection(userConsumeDBName).doc(consumeId).remove()
}

// 删除补贴记录
function removeAllowenceRecord(allowenceId) {
	if (objIsEmpty(allowenceId)) {
		return false
	}
	db.collection(userAllowenceDBName).doc(allowenceId).remove()
}

//修改商户的备付金:补贴之后都是减少对应的备付金
function removeAllowenceRecord(business_id, amountFen) {

}

// 获取用户详情
async function getBusinessInfo(business_id) {
	const bsResult = await db.collection(businessInfoDBName).where({
		offlineBusinessId: business_id
	}).limit(1).get()
	let exist = unicloudDataExist(bsResult)
	if (exist) {
		return bsResult.data[0]
	}
	return null
}

// 修改商户备付金
async function updateBusinessReserveAmount(business_id, amountFen) {
	if (amountFen == 0) {
		console.log('金额为0，无需修改');
		return false
	}
	let bsinfo = await getBusinessInfo(business_id)
	if (bsinfo == null) {
		console.log(business_id + '商户不存在');
		return false
	}
	let bsinfoAmount = bsinfo.reserve_amount - amountFen
	await db.collection(businessInfoDBName).doc(bsinfo._id).update({
		reserve_amount: bsinfoAmount
	})
	return true
}

// 添加排队队列
async function addQueue(event) {
	/*
	{
		business_id,user_id,consume_order,order_time,isDelete
	}
	*/
	// 判断用户是否已经在排队
	let queueUser = await getQueueUser(event.business_id, event.user_id)
	if (queueUser != null) {
		console.log('该用户已经在商家排队，无需重复排队');
		return 0
	}
	// consume_order：根据business_id查询出改店家正在排队的记录的最大值，然后+1即可
	let maxConsumeOrder = await getMaxConsumeOrder(event.business_id)
	let addQueueParam = {
		business_id: event.business_id,
		user_id: event.user_id,
		consume_order: maxConsumeOrder + 1,
		order_time: event.pay_time,
		isDelete: 0
	}
	let addResult = await db.collection(queueDBName).add(addQueueParam)
	if (objIsEmpty(addResult)) {
		return false
	}
	if (addResult._id == null || addResult == undefined || addResult == '') {
		return false
	}
	return addResult
}

// 获取某商家的最大排队数字
async function getMaxConsumeOrder(business_id) {
	let result = await db.collection(queueDBName).where({
		business_id: business_id
	}).orderBy('consume_order', 'desc').limit(1).get()

	let exist = unicloudDataExist(result)
	if (exist) {
		return result.data[0].consume_order
	}
	return 0
}

// 获取A商家B用户正在排队的对象，没有返回null
async function getQueueUser(business_id, user_id) {
	if (objIsEmpty(business_id)) {
		console.log('参数为空');
		return null
	}
	if (objIsEmpty(user_id)) {
		console.log('参数为空');
		return null
	}
	let result = await db.collection(queueDBName).where({
		business_id: business_id,
		user_id: user_id
	}).limit(1).get()
	let exsit = unicloudDataExist(result)
	if (exsit) {
		return result.data[0]
	}
	return null
}

// 修改消费记录状态
async function updateUserConsumeStatus(business_id, user_id, status) {
	console.log(business_id, user_id, status);
	if (objIsEmpty(business_id) || objIsEmpty(user_id) || objIsEmpty(status)) {
		console.log('参数不齐');
		return false
	}
	let userConsumeRecord = await getUserComsumeByAllowencing(business_id, user_id)
	if (userConsumeRecord == null) {
		console.log('不存在补贴中的消费记录');
		return null
	}
	console.log('11111111111');
	console.log(JSON.stringify(userConsumeRecord));
	await db.collection(userConsumeDBName).doc(userConsumeRecord._id).update({
		consume_status: status
	})
	return true
}

// 删除队列(逻辑删除)：当消费记录状态为 已完成 或者 已退出 时，将此排队的队列删除
async function removeQueueIfExitOrFinished(business_id, user_id) {
	// 判断是否存在补贴中的消费记录，存在则不删除
	let allowencingRecord = getUserComsumeByAllowencing(business_id, user_id)
	if (allowencingRecord != null) {
		console.log('存在补贴中的，不删除');
		return false
	}
	await db.collection(queueDBName).where({
		business_id: business_id,
		user_id: user_id,
		isDelete: 1
	})
	return true
}
//=========================================================非主函数======================================================//